<template>
  <div class="main gap16 flex-column">
    <div class="top bg-white">
      <div class="bold mgb10">故障客户概览</div>
      <div class="gap30 flex-row-center-between">
        <TopOverviewMonth :data="state.data.faultCustomerVO" />
        <TopOverviewAll :data="state.data.faultCustomerVO" class="flex1" />
      </div>
    </div>
    <div class="flex flex1 gap16" style="height: calc(100% - 190px)">
      <div class="bg-white flex-column flex1">
        <div style="height: 40px" class="flex-row-center-between">
          <span class="bold">故障客户分布</span>
          <el-link v-if="state.data?.distributionVOList?.length" type="primary" @click="toPageAllList"> 查看更多 </el-link>
        </div>
        <div v-if="state.data?.distributionVOList?.length" class="flex1" style="overflow: auto">
          <DistributionItem v-for="item in state.data.distributionVOList.slice(0, 10)" :key="item.customerName" class="mgb20" :data="item" @customer-name-click="onCustomerNameClick" />
        </div>

        <empty v-else style="margin: auto" />
      </div>

      <div class="flex-column right-box gap16">
        <div class="flex-column flex1 bg-white">
          <div class="flex-row-center-left gap10">
            <div class="bold">线均故障分布</div>
            <el-popover ref="popEl" placement="right" :width="400" trigger="click">
              <template #reference>
                <el-icon color="#A4AEC4"><Setting /></el-icon>
              </template>
              <GraphSettingLine :config-data="state.linePieConfig" @cancel="hideLineConfigPop" @handle-confirm="confirmLineConfig" @reset="handlResetLineConfig" />
            </el-popover>
          </div>
          <div id="graph-line-avg" class="flex1 width-all"></div>
          <empty v-if="!state.data?.distributionVOList?.length" style="margin: auto" />
        </div>

        <div class="flex-column flex1 bg-white">
          <div class="flex-row-center-left gap10">
            <div class="bold">客户首次故障时间分布</div>
            <el-popover ref="popFirstEl" placement="right" :width="400" trigger="click">
              <template #reference>
                <el-icon color="#A4AEC4"><Setting /></el-icon>
              </template>
              <GraphSettingFirst :config-data="state.firstTimePieConfig" @cancel="hideFirstConfigPop" @handle-confirm="confirmFirstConfig" @reset="handlResetFirstConfig" />
            </el-popover>
          </div>
          <div id="graph-first-time" class="flex1 width-all"></div>
          <empty v-if="!state.data?.distributionVOList?.length" style="margin: auto" />
        </div>

        <div class="flex1 flex-column width-all bg-white">
          <div class="bold">最长连续发生故障分布</div>
          <div id="graph-persist" class="flex1 width-all"></div>
          <empty v-if="!state.data?.distributionVOList?.length" style="margin: auto" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted, onUnmounted, nextTick } from 'vue'
  import * as echarts from 'echarts'
  import { clone } from 'xe-utils'
  import TopOverviewAll from './cpns/top-overview-all.vue'
  import TopOverviewMonth from './cpns/top-overview-month.vue'
  import DistributionItem from './cpns/distribution-item.vue'
  import GraphSettingLine from './cpns/graph-setting-line.vue'
  import GraphSettingFirst from './cpns/graph-setting-first.vue'
  import request from '@/service'
  import router from '@/router'
  import { Ui, cache } from '@/utils'
  import { setPieChartOptions, setBarChartOptions } from './config'
  import type { FaultCustomerData, FaultOverview, FaultDistribution, PieData, IGraphSetConfig } from './config'
  import type { ECharts } from 'echarts'
  import type { PopoverInstance } from 'element-plus'
  import empty from '@/components/empty/empty.vue'

  const popEl = ref<PopoverInstance>()
  const popFirstEl = ref<PopoverInstance>()

  const defaultLinePieConfig: IGraphSetConfig[] = [
    { s: 1, e: 10 },
    { s: 11, e: 30 },
    { s: 31, e: 50 },
    { s: 51, e: null }
  ]

  const defaultFirstPieConfig: IGraphSetConfig[] = [
    { s: 1, e: 1 },
    { s: 2, e: 2 },
    { s: 3, e: 3 },
    { s: 4, e: 6 },
    { s: 7, e: 12 }
  ]

  const cacheLinePieConfig = cache.get<IGraphSetConfig[]>('graphCustomerLine')
  const cacheFirstPieConfig = cache.get<IGraphSetConfig[]>('graphCustomerFirst')

  const state = reactive({
    data: {
      faultCustomerVO: {} as FaultOverview,
      distributionVOList: [] as FaultDistribution[]
    },
    linePieConfig: cacheLinePieConfig?.length ? cacheLinePieConfig : clone(defaultLinePieConfig, true),
    firstTimePieConfig: cacheFirstPieConfig?.length ? cacheFirstPieConfig : clone(defaultFirstPieConfig, true),
    persistBarConfig: [2, 3, 4, 5, 8]
  })

  let lineAvgEchart: ECharts
  let firstTimeEchart: ECharts
  let persistEchart: ECharts

  /**----------------------------methods----------------------------------------------------------------------- */

  const confirmLineConfig = () => {
    mapLineAvgEchartData()
    hideLineConfigPop()
  }

  const handlResetLineConfig = () => {
    state.linePieConfig = clone(defaultLinePieConfig, true)
    cache.remove('graphCustomerLine')
    confirmLineConfig()
  }

  const confirmFirstConfig = () => {
    mapFirstTimeEchartData()
    hideFirstConfigPop()
  }

  const handlResetFirstConfig = () => {
    state.firstTimePieConfig = clone(defaultFirstPieConfig, true)
    cache.remove('graphCustomerFirst')
    confirmFirstConfig()
  }

  const hideFirstConfigPop = () => popFirstEl.value?.hide()
  const hideLineConfigPop = () => popEl.value?.hide()

  /**跳转故障清单 */
  const onCustomerNameClick = (data: FaultDistribution) => {
    const { customerName } = data
    router.push({
      path: '/fault/list',
      query: {
        customerName
      }
    })
  }

  const resize = () => {
    lineAvgEchart.resize()
    firstTimeEchart.resize()
    persistEchart.resize()
  }

  /**初始化图 */
  const initGraph = () => {
    lineAvgEchart = echarts.init(document.getElementById('graph-line-avg'))
    firstTimeEchart = echarts.init(document.getElementById('graph-first-time'))
    persistEchart = echarts.init(document.getElementById('graph-persist'))

    window.addEventListener('resize', resize)
  }

  /**查看更多 */
  const toPageAllList = () => {
    router.push({
      path: '/fault/statistic-customer/cpns/view-list-all'
    })
  }

  /**线均故障分布 */
  const mapLineAvgEchartData = () => {
    const data: PieData[] = []

    state.linePieConfig.forEach(item => {
      const list = state.data.distributionVOList.filter(fault => {
        if (item.e) return fault.totalFault >= item.s && fault.totalFault <= item.e
        return fault.totalFault >= item.s
      })

      data.push({
        name: item.e ? `${item.s}-${item.e}` : `${item.s}-`,
        value: list.length
      })
    })

    setPieChartOptions(lineAvgEchart, data)
  }

  /**客户首次故障时间分布 */
  const mapFirstTimeEchartData = () => {
    const data: PieData[] = []

    state.firstTimePieConfig.forEach(item => {
      const list = state.data.distributionVOList.filter(fault => {
        if (item.s !== item.e) return fault.startMonth >= item.s && fault.startMonth <= (item.e as number)
        return fault.startMonth === item.s
      })

      data.push({
        name: item.s === item.e ? `${item.s}` : `${item.s}-${item.e}`,
        value: list.length
      })
    })

    setPieChartOptions(firstTimeEchart, data)
  }

  /**最长连续发生故障分布 */
  const mapPersistEchartData = () => {
    const data: number[] = []

    state.persistBarConfig.forEach(item => {
      const list = state.data.distributionVOList.filter(fault => fault.duringMonth === item)

      data.push(list.length)
    })

    setBarChartOptions(persistEchart, state.persistBarConfig, data)
  }

  /**获取数据 */
  const query = () => {
    request.get<FaultCustomerData>('/fault/getFaultCustomer').then(res => {
      if (res.code !== 0) return Ui.useMessage('error', res.msg)
      state.data = res.data

      if (!res.data.distributionVOList.length) return

      nextTick(() => {
        initGraph()

        mapLineAvgEchartData()

        mapFirstTimeEchartData()

        mapPersistEchartData()
      })
    })
  }

  /**----------------------------lifecycle----------------------------------------------------------------------- */
  onMounted(() => {
    query()
  })

  onUnmounted(() => {
    lineAvgEchart.dispose()
    firstTimeEchart.dispose()
    persistEchart.dispose()
    window.removeEventListener('resize', resize)
  })
</script>

<style scoped lang="less">
  .main {
    background: #f2f6fc !important;
    gap: 16px;
    padding: 0;
    .bg-white {
      padding: 10px;
      background: #fff;
    }
    // .top {
    //   height: 170px;
    // }
    .right-box {
      width: 500px;
    }
  }
</style>
